//
//  ZoomViewController.m
//  WebImageShow
//
//  Created by 李志权 on 15/7/23.
//  Copyright (c) 2015年 BW. All rights reserved.
//

#import "ZoomViewController.h"
#import "Utils.h"
#import "HUD_SingleCase.h"
#import "UIImageView+WebCache.h"
#import "UIButton+WebCache.h"
#import "SDWebImageManager.h"
#import "ImageCompress.h"
@interface ZoomViewController ()
{
    int _index;//当前图片索引
    int flag;//图片不在当前页面还原
    NSMutableArray *_imaArray;//图片数组
}
@end

@implementation ZoomViewController

- (id)initWithUIImageView:(NSMutableArray *)wbeImage index:(int)index
{
    self = [super init];
    
    self.navigationItem.title = [NSString stringWithFormat:@"%d / %d",index+1,(int)wbeImage.count];

    //保存数据
    _index = index;
    _imaArray = [NSMutableArray arrayWithArray:wbeImage];
    for (int a = 0; a<_imaArray.count; a++) {
        if ([_imaArray[a] isKindOfClass:[SDNetImageView class]]) {
            SDNetImageView *tmpView = _imaArray[a];
            NSMutableString *url = [NSMutableString stringWithFormat:@"%@",tmpView.imageURL];
            NSRange range = [url rangeOfString:@"thumbcrop/"];
            if (range.location != NSNotFound) {
                [url deleteCharactersInRange:NSMakeRange(range.location, range.length)];
            }
            [_imaArray removeObjectAtIndex:a];
            [_imaArray insertObject:url atIndex:a];
        }
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor];
    
    
    self.scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0,0, Width+20, Height-64)];
    self.scroll.delegate = self;
    self.scroll.pagingEnabled = YES;

    [self.view addSubview:self.scroll];
    
    for (int a = 0; a<_imaArray.count; a++)
    {
        UIScrollView *scroll = [self ImageName:_imaArray[a] viewTag:700+a];
        scroll.frame = CGRectMake((Width+20)*a, 0, self.scroll.bounds.size.width-20, self.scroll.bounds.size.height);
        [self.scroll addSubview:scroll];
    }
    
    self.scroll.contentSize = CGSizeMake(_imaArray.count*(Width+20), Height-64);
    self.scroll.contentOffset = CGPointMake((Width+20)*_index, 0);
    
    if (self.options == 0) {
        UIBarButtonItem *rightBar1 = [[UIBarButtonItem alloc]initWithTitle:@"旋转" style:UIBarButtonItemStylePlain target:self action:@selector(rotateImage:)];
        rightBar1.tintColor = MAINBLUESYSTEM;
        
        
        UIBarButtonItem *rightBar = [[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveThepPicture)];
        rightBar.tintColor = MAINBLUESYSTEM;
        
        [self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:rightBar1,rightBar, nil] animated:YES];
    }
    else
    {
        UIBarButtonItem *rightBar1 = [[UIBarButtonItem alloc]initWithTitle:@"旋转" style:UIBarButtonItemStylePlain target:self action:@selector(rotateImage:)];
        rightBar1.tintColor = MAINBLUESYSTEM;
        
        [self.navigationItem  setRightBarButtonItem:rightBar1 animated:YES];
        
            self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    
    // Do any additional setup after loading the view.
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.type.hidden = NO;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)rotateImage:(UIBarButtonItem *)rightBar1
{

    rightBar1.enabled = NO;
    UIScrollView *smallScrollView = [self.scroll.subviews objectAtIndex:_index];
    UIImageView *tempImage = [[smallScrollView subviews] objectAtIndex:0];
    
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        if (tempImage.image.size.width >= 1000 || tempImage.image.size.height >= 1000)
        {
            tempImage.image = [ImageCompress imageCompressForAuto:tempImage.image targetWidth:1000];
        }
        
        tempImage.image = [ImageCompress rotateImage:tempImage.image rotation:UIImageOrientationRight];
        
        rightBar1.enabled = YES;
    });
    
    

}

/**
 参数图片名字
 viewTag值
 */
- (UIScrollView *)ImageName:(id)iamg viewTag:(NSInteger)tag
{
    UIScrollView *scroll = [[UIScrollView alloc]init];
    scroll.maximumZoomScale  = 3.0;
    scroll.minimumZoomScale  = 1.0;
    scroll.delegate = self;
    if ([iamg isKindOfClass:[NSString class]]) {
        UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, Width, Height-64)];
        img.contentMode = UIViewContentModeScaleAspectFit;
        [scroll addSubview:img];
        UIView *HUD = [[HUD_SingleCase HUDALLOW] HUDDialogUntil:nil];
        [img addSubview:HUD];
        [img sd_setImageWithURL:[NSURL URLWithString:iamg]
               placeholderImage:[UIImage imageNamed:@"ic_failure_"]
                      completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                          img.frame = CGRectMake(0, 0, self.scroll.bounds.size.width-20, self.scroll.bounds.size.height);
                          [HUD removeFromSuperview];
                      }];

    }
    else if ([iamg isKindOfClass:[UIImageView class]])
    {
        UIImageView *tmpImage = iamg;
        UIImageView *img = [[UIImageView alloc]initWithImage:tmpImage.image];
        img.frame = CGRectMake(0, 0, self.scroll.bounds.size.width-20, self.scroll.bounds.size.height);
        img.contentMode = UIViewContentModeScaleAspectFit;
        [scroll addSubview:img];
    }
    //双击放大
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(finger_double:)];
    tap2.numberOfTapsRequired = 2;
    [scroll addGestureRecognizer:tap2];
    
    //加上手势点击退出控制器
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self.navigationController action:@selector(popViewControllerAnimated:)];
        [scroll addGestureRecognizer:tap];
    
       [tap requireGestureRecognizerToFail:tap2];
    return scroll;
    
    
}

//双击放到最大
- (void)finger_double:(UITapGestureRecognizer *)tap
{
    UIScrollView *scroll = (UIScrollView *)tap.view;
    if (scroll.zoomScale == 1.0) {
        [UIView animateWithDuration:0.25 animations:^{
            scroll.zoomScale = 3.0;
        }];
    }
    else
    {
        [UIView animateWithDuration:0.25 animations:^{
            scroll.zoomScale = 1.0;
        }];
    }
}
//保存图片
- (void)saveThepPicture
{
    switch (self.options) {
        case 0:
        {
            UIScrollView *smallScrollView = [self.scroll.subviews objectAtIndex:_index];
            UIImageView *tempImage = [[smallScrollView subviews] objectAtIndex:0];
            //将该图像保存到媒体库中
            UIImageWriteToSavedPhotosAlbum(tempImage.image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
            break;
        }
        
        default:
            break;
    }
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (!error)
    {
        UIAlertView *aler = [[UIAlertView alloc]initWithTitle:@"提示" message:@"图片保存成功" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [aler show];
    }
    else
    {
        UIAlertView *aler = [[UIAlertView alloc]initWithTitle:@"提示" message:@"图片失败" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [aler show];
    }
    
    
}
#pragma mark UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView == self.scroll)
    {
        NSInteger currentPage = self.scroll.contentOffset.x / self.view.frame.size.width;
        _index = (int)currentPage;
//        _index = currentPage;
        
        self.navigationItem.title = [NSString stringWithFormat:@"%d / %d", (int)currentPage+1, (int)_imaArray.count];
        
        if (currentPage != flag)
        {
            UIScrollView *smallScrollView = [self.scroll.subviews objectAtIndex:flag];
            smallScrollView.zoomScale = 1.0;
            flag = (int)currentPage;
        }
        
    }
    
}
//滚动视图放大缩小相关的回调
//返回放大缩小的视图
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    if (scrollView != self.scroll)
    {
        UIView *subView = [[scrollView subviews] objectAtIndex:0];
        return subView;
    }
    
    return nil;
}

//视图正在缩放中
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    if (scrollView != self.scroll)
    {
        //获取当前的缩放图片
        UIImageView *tempImage = [[scrollView subviews] objectAtIndex:0];
        
        //重置位置
        CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width)?
        (scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5 : 0.0;
        CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height)?
        (scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5 : 0.0;
        tempImage.center = CGPointMake((int)(scrollView.contentSize.width * 0.5 + offsetX),
                                       (int)(scrollView.contentSize.height * 0.5 + offsetY));
    }
}

//视图开始缩放
- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view
{
    self.scroll.scrollEnabled = NO;//缩放时禁止外层大scrollview的滚动
}

//视图结束缩放
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
{
    self.scroll.scrollEnabled = YES;//缩放结束时打开外层大scrollview的滚动
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
